﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace POSPlus.BTxmlWriter
{
    public class TreeToXmlConverter
    {
        public Tree<String> NodeTree { get; private set; }
        public XmlDocument Document { get; private set; }
        public XmlTextWriter Writer { get; private set; }

        public TreeToXmlConverter(Tree<String> nodeTree, XmlDocument document)
        {
            NodeTree = nodeTree;
            //Document = document;
        }

        public void Convert()
        {
            Document = new XmlDocument();
            Document.AppendChild(BuildStructure(NodeTree.Root));
        }

        /// <summary>
        /// Writes the document to the given file.
        /// </summary>
        /// <param name="fileLocation"></param>
        public void WriteToFile(String fileLocation)
        {
            Writer = new XmlTextWriter(fileLocation, Encoding.UTF8);
            Writer.WriteStartDocument();
            Document.WriteTo(Writer);
            Writer.WriteEndDocument();
            Writer.Close();
        }

        /// <summary>
        /// Recursive function that traverses a Tree and converting each Node to an XmlElement with the correct
        /// InnerValue and Attributes set.
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private XmlNode BuildStructure(Node<String> node)
        {
            XmlNode result = Document.CreateNode(XmlNodeType.Element, node.Name, null);
            result.InnerText = node.Value;
            Console.WriteLine(node.ToString());

            foreach (KeyValuePair<String, String> attribute in node.Attributes)
            {
                result.Attributes.Append(Document.CreateAttribute(attribute.Key));
                result.Attributes[attribute.Key].Value = attribute.Value;
            }

            foreach (Node<String> child in node.Children.Values)
            {
                result.AppendChild(BuildStructure(child));
            }

            return result;
        }

        public void LoadAndModify(string xmlLocation, string path, string innerValue)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlLocation);
            XmlNode node = doc.SelectSingleNode(path);
            node.InnerText += innerValue;
            Writer = new XmlTextWriter(xmlLocation, Encoding.UTF8);
            doc.WriteContentTo(Writer);
            Writer.Close();
        }

        public void LoadAndClip(string xmlLocation, string path)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlLocation);
            XmlNode node = doc.SelectSingleNode(path);
            node.InnerText.TrimEnd();
            Writer = new XmlTextWriter(xmlLocation, Encoding.UTF8);
            doc.WriteContentTo(Writer);
            Writer.Close();
        }
    }
}
